package com.csdj.t301.cloud.uitls;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.Iterator;
import java.util.List;


/**
 * author:cloud
 * date:2021/1/26 0026
 **/
public class Dom4jParser {

    public static void main(String[] args) {
        Document doc = loadXml("resources/xml/phoneInfo.xml");
        showXml(doc);
    }


    public static Document loadXml(String filename){
        try {
            SAXReader reader = new SAXReader();
            return reader.read(filename);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 显示xml文件内容
     * @param doc
     */
    public static void showXml(Document doc){
        Element root = doc.getRootElement();
        Element id = root.elementByID("iphone");
        if(id != null){
            List<Attribute> list = id.attributes();
            for(Attribute obj : list){
                System.out.println(obj.getName()+"  "+obj.getValue());
            }
        }else{
            System.out.println("id is null");
        }
        Iterator iterator = root.elementIterator();
        while(iterator.hasNext()){
            Element next = (Element) iterator.next();
            System.out.println(next.getName());
            System.out.println(next.getText());
        }

    }

    public static void saveXml(Document doc, String filename){
        try {
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(filename),"utf-8"));
            writer.write(doc);
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
